<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科室名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入科室名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格展示 -->
    <el-table v-loading="loading" :data="depList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="科室id" align="center" width="100" type="index" />
      <el-table-column label="科室名称" align="center" prop="name" />
      <el-table-column label="科室描述" align="center" prop="description" />
      <el-table-column label="科室所属医生数量" align="center" prop="doctorsNum" />
      <el-table-column label="科室所属医院" align="center" prop="hospitalName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleShowDoc(scope.row)">
            详情医生
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[1, 3, 10, 20]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="850px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="科室描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入对科室的描述" />
        </el-form-item>
        <el-form-item label="医生数量">
          <el-input v-model="form.doctorsNum" disabled placeholder="科室所属医生数量" />
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择医院" size="large" style="width: 240px"
            @change="handleHospitalChange">
            <el-option v-for="item in hospitalsOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">
            确 定
          </el-button>
          <el-button @click="cancel">
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { addDep, delDep, getDep, listDep, updateDep } from "../../api/bigDep/bigDep.js";
import router from "../../router/index.js";

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 医院列表数据
const depList = ref([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);

// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 10,
  name: null,
  queryString: null,
});

// 选择查询条件
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = ref({
  id: null,
  name: null,
  doctorsNum: 0,
  description: null,
  hospitalId: null,
});

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入科室描述', trigger: 'blur' }
  ],
  hospitalId: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ]
});

// 表单引用
const formRef = ref(null);
const queryFormRef = ref(null);

// 省的选项数据数组
const hospitalsOptions = ref([]);

function findHospitals() {
  axios({
    url: '/hospital/findHospitals',
    method: 'get',
  }).then((res) => {
    console.log(res);
    hospitalsOptions.value = res.data.data;
  });
}
function handleHospitalChange(hospitalId) {
  // 获取选中的 id (hospitalId)
  console.log('Selected province ID:', hospitalId);
  form.value.hospitalId = hospitalId;
  // 获取选中的 name
  const selectedHospital = hospitalsOptions.value.find(
    (hospital) => hospital.id === hospitalId
  );

  if (selectedHospital) {
    console.log('Selected province name:', selectedHospital.name);
    //  你可以在这里将 selectedProvince.name 存储到 data 中，以便在其他地方使用
    form.value.hospitalName = selectedHospital.name; // 例如，添加到 form 对象
  }
}
// 获取列表数据
const getList = async () => {
  selectQueryCondition();
  loading.value = true;
  try {
    const res = await listDep(queryParams.value);
    depList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表数据失败:', error);
  } finally {
    loading.value = false;
  }
};



/**
 * 分页
 */
// 添加分页处理方法
// 页面大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val;
  getList();
}

// 取消按钮操作
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    name: null,
    doctorsNum: 0,
    description: null,
    hospitalId: null,
  };
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.currentPage = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};

// 多选框选中数据处理
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  title.value = '添加';
  open.value = true;
};

// 修改按钮操作
const handleUpdate = async (row) => {
  reset();
  const id = row?.id || ids.value[0];
  if (!id) {
    console.error('未选择有效的医院信息');
    return;
  }

  try {
    const res = await getDep(id);
    console.log('获取到的科室数据:', res);
    if (res.code === 200) {
      form.value = res.data;
      title.value = '修改';
      open.value = true;
    } else {
      alert('获取科室信息失败：' + res.msg);
    }
  } catch (error) {
    console.error('获取科室信息失败:', error);
    alert('获取科室信息失败，请稍后重试');
  }
};

// 提交表单操作
const submitForm = async () => {
  if (formRef.value) {
    try {
      await formRef.value.validate();
      if (form.value.id !== null) {
        const res = await updateDep(form.value);
        if (res.code === 200) {
          open.value = false;
          getList();
          alert('修改成功');
        } else {
          alert(`修改失败: ${res.msg}`);
        }
      } else {
        const res = await addDep(form.value);
        if (res.code === 200) {
          open.value = false;
          getList();
          alert('新增成功');
        } else {
          alert(`新增失败: ${res.msg}`);
        }
      }
    } catch (error) {
      console.error('表单校验失败:', error);
    }
  }
};

// 删除按钮操作
const handleDelete = async (row) => {
  const id = row?.id || ids.value;
  const confirmResult = confirm(`是否确认删除编号为"${id}"的数据项？`);
  if (confirmResult) {
    try {
      const res = await delDep(id);
      if (res.code === 200) {
        getList();
        alert('删除成功');
      } else {
        alert(`删除失败: ${res.msg}`);
      }
    } catch (error) {
      console.error('删除医院信息失败:', error);
    }
  }
};

const handleShowDoc = async (row) => {
  console.log("row" + row.id);
  // router.push("/showDoc")
  router.push({
    name: 'showDepDoc',
    params: {
      id: row.id,
      name: row.name,
      hospitalName: row.hospitalName
    }
  });
}

onMounted(() => {
  getList();
  findHospitals();
});
</script>
